package cn.turing.firecontrol.datahandler.modbus.entity;

import com.serotonin.io.serial.SerialParameters;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;

/**
 * @Classname ModbusRTUOp
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/6/27 18:18
 * @Created by wupenghao
 */
public class ModbusRTUOp {
    public static ModbusMaster master;
    // 设定MODBUS网络上从站地址
    public final static int SLAVE_ADDRESS = 1;
    //串行波特率
    public final static int BAUD_RATE = 9600;

    public static void init() throws Exception{
        /* 创建ModbusFactory工厂实例 */
        ModbusFactory modbusFactory = new ModbusFactory();
        /* 创建ModbusMaster实例 */
        SerialParameters serialParameters=new SerialParameters();
        // 设定MODBUS通讯的串行口
        serialParameters.setCommPortId("COM6");
        // 设定成无奇偶校验
        serialParameters.setParity(0);
        // 设定成数据位是8位
        serialParameters.setDataBits(8);
        // 设定为1个停止位
        serialParameters.setStopBits(1);
        // 设定端口名称
        serialParameters.setPortOwnerName("Numb nuts");
        // 设定端口波特率
        serialParameters.setBaudRate(BAUD_RATE);
        master = modbusFactory.createRtuMaster(serialParameters);
        master.init();
    }
    public static void destroy() throws Exception {
        master.destroy();
    }

    /**
     * 批量读保持寄存器上的内容
     *
     * @param slaveId 从站地址
     * @param start   起始地址的偏移量
     * @param len     待读寄存器的个数
     */
    public static short[] batchReadHoldingRegisters(int slaveId, int start, int len) throws Exception {
        ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(slaveId, start, len);
        ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) master.send(request);
        return response.getShortData();
    }

}
